<?php
abstract class ss_doctrine_record extends Doctrine_Record{
	public $inresponse=false;
	protected $ss_fullrefs=false;
	protected $prefix='/api';
	
	protected $ss_refcols=array();
	/*
    public function ss_setTableDefinition()
    {
		//parent::setTableDefinition();
        $this->mapValue('$ref');
    }*/
	public function ss_setUp(){
		//parent::setUp();
		//$this->hasAccessorMutator('$ref', 'getRef','setRef');
		//$this->hasAccessorMutator('id', 'getRef','setRef');
		//$this->hasAccessor('id', 'getRef');
		//$this->hasMutator('date_pub', 'setDatePub');
	}

	public function getRef($prefix=''){
		$result=$prefix.'/'.get_class($this).'/'.implode('_',$this->identifier());
		//ss_error::log($this->identifier());
		//$result='/'.get_class($this).'/'.$this->_get('id');
		//$result=$this->_get('id')+5;
		//ss_error::log($this->getTable()->getTableName(),'Accessor');
		return $result;
	}
	
	public function setDatePub($value){
		if(is_string($value)){
			$this->_set('date_pub',strtr(trim($value,'Z'),'T',' '));
		} elseif(is_null($value)||empty($value)){
			$this->_set('date_rej',NULL);
		}
		//ss_error::log($this->_get('date_pub'),'Date pub mutator');
	}
	
	public function setDateRej($value){
		if(is_string($value)){
			$this->_set('date_rej',strtr(trim($value,'Z'),'T',' '));
		} elseif(is_null($value)||empty($value)){
			$this->_set('date_rej',NULL);
		}
		//ss_error::log($this->_get('date_rej'),'Date rej mutator');
	}

	public function setRef($value){
		if(!is_numeric($value)){
			$idparts=explode('_',end(explode('/',$value)));
			ss_error::log($idparts,'Setting id to');
			/*foreach(array_keys($this->identifier()) as $pos=>$key){
				$this->_set($key, $idparts[$pos]);
			}*/
			$this->_set('id', $idparts[0]);
		} else {
			ss_error::log($value,'Setting id to');
			$this->_set('id', $value);
		}
		return $this;
	}
	
	public function refToId($ref,$table=null){
		if(!is_numeric($ref)){
			$split=explode('#',$ref);
			$split=explode('/',current($split));
			$idparts=explode('_',end($split));
			//ss_error::log($idparts,'Setting id to');
			if(count($idparts)==1) return current($idparts);
			ss_error::log(Doctrine::getTable($table)->getIdentifier(),'Transform ref from table');
			
			return array_combine(Doctrine::getTable($table)->getIdentifier(),$idparts);
		} else {
			return $ref;
		}
	}
	public function sanitize($data,$table=null){
		//$data=$this->fixRelations($data);
		//ss_error::log($data);
		if(isset($data['created_at'])) unset($data['created_at']);
		if(isset($data['updated_at'])) unset($data['updated_at']);
		foreach($data as $key=>$val){
			if(is_array($val)){
				if(isset($val['$ref'])){
					$data[$key]=$this->refToId($val['$ref'],(is_numeric($key)?$table:$key));
				} else {
					$data[$key]=$this->sanitize($val,$key);
				}
			} elseif($key=='id'){
				$data[$key]=$this->refToId($val);
			}
		}
		return $this->fixRelations($data);
	}
	
	public function fixRelations($data){
		foreach($this->getReferences() as $name=>$ref){
			if(get_class($ref)!='Doctrine_Collection'){
				if(isset($data[$name])) {
					//$lowname=strtolower($name).'_id';
					ss_error::log($name,'Unsetting single relation');
					$data[strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $name)).'_id']=$data[$name];
					unset($data[$name]);
				}
			}
		}
		return $data;
	}
	
	protected function l1hydrate($base,$wide=false,$version=null,$prefix='/api'){
							//ss_error::log($base,'Base check');
		if($this->inresponse){
			$base=array('$ref'=>$this->getRef($prefix));
		} else {
					//ss_error::log($base);
			$this->inresponse=true;
			//$base=$this->toArray($wide);
			//ss_error::log(array_keys($this->getAccessors()));
			try{
				if(is_array($accessors=$this->getAccessors())){
					foreach($accessors as $key=>$func){
						if($key==='id') {
							$base[$key]=$this->{$func}($prefix);
						} else {
							$base[$key]=$this->{$func}();
						}
					}
				}
			} catch(Exception $e){
				
			}
			/*
			if(is_object($accessors=$this->getAccessors())){
				foreach($this->getAccessors() as $key=>$func){
					if($key==='id') {
						$base[$key]=$this->{$func}($prefix);
					} else {
						$base[$key]=$this->{$func}();
					}
				}
			}*/
			//ss_error::log(array_keys($this->getReferences()),'Relations');
			foreach($this->getReferences() as $name=>$ref){
				//ss_error::log($name,'Reference');
				if($name=='Translation') {
					//if(!$wide)$base[$name]=array();
					$base[$name]=$this->ss_getTranslation(($wide?$base[$name]:array()),$wide,$version,$prefix);
					continue;
				}
				$lowname=strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $name)).'_id';
				if(is_subclass_of($ref,'Doctrine_Collection')){
					//ss_error::log($name,'Is Collection');
					$base[$name]=array();
					foreach($ref as $pos=>$obj){
						if($wide){
							/*ss_error::log($name,'Relation');
							ss_error::log($base[$name][$pos],'Position');
							ss_error::log(get_class($obj),'Class');
							ss_error::log($result,'Result');*/
							$base[$name][(integer)$pos]=$obj->l1hydrate($base[$name][$pos],false,$version,$prefix);
						} else {
							$base[$name][(integer)$pos]=array('$ref'=>$obj->getRef($prefix));
						}
					}
				} elseif(get_class($ref)=='Doctrine_Null'){
					//ss_error::log($base,'Null Class for '.$name);
					$base[$name]=null;
					unset($base[$lowname]);
				} else {
					if($wide){
						$base[$name]=$ref->l1hydrate($base[$name],false,$version,$prefix);
					} else {
						$base[$name]=array('$ref'=>$ref->getRef($prefix));
					}
					unset($base[$lowname]);
				}
				//ss_error::log(get_class($ref),'Handling '.$name);
				if(is_array($ref)) ss_error::log($name,'Is array');
			}
		}
		//ss_error::log($this->getAccessors());
		return $base;
	}
	protected function ss_getTranslation($base,$wide=false,$lang=null,$prefix='/api'){
		//return $base;
		//$result=array();
		if($lang){
			if(!$wide) $base[$lang]=$this['Translation'][$lang]->toArray();
			$base[$lang]['id']=($this->getRef($prefix).'#Translation.'.$lang);
			//unset($base[$lang]['id']);
			//$result[$lang]['id']=$prefix.$this['$ref'].'/'.$lang;
		} else {
			if(!$wide) $base=$this['Translation']->toArray(true);
			//foreach($base as $l=>$data) unset($base[$l]['id']);//$result[$l]['id']=$prefix.$this['$ref'].'/'.$l;
			foreach($base as $l=>$data) $base[$l]['id']=($this->getRef($prefix).'#Translation.'.$l);
		}
		return $base;
	}
	
	public function getJSONData($wide=false,$version=null,$prefix='/api'){
		return $this->l1hydrate($this->toArray($wide),$wide,$version,$prefix);
	}
	
	
	public function debugRelations(){
		$relations=$this->getTable()->getRelations();
		foreach($relations as $kay=>$value){
			print($value);
		}
	}
}

class ss_doctrine_recordTable extends Doctrine_Table{
	
}
?>